package com.qf.smsplatform.gateway.netty4;

import com.qf.smsplatform.common.model.StandardSubmit;
import com.qf.smsplatform.gateway.mq.MTQueue;
import com.qf.smsplatform.gateway.mq.StatQueue;
import com.qf.smsplatform.gateway.netty4.Utils.MsgUtils;
import com.qf.smsplatform.gateway.netty4.entity.CmppDeliver;
import com.qf.smsplatform.gateway.netty4.entity.CmppSubmitResp;
import com.qf.smsplatform.gateway.netty4.entity.ControlWindow;
import com.qf.smsplatform.gateway.netty4.entity.ReportMatch;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * 主要业务 handler
 * @author weixiang
 * @date 2018/8/2 15:37
 */

public class CMPPHandler extends SimpleChannelInboundHandler {
    private final static Logger log = LoggerFactory.getLogger(CMPPHandler.class);

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {

        // 第一次响应
        if (msg instanceof CmppSubmitResp){
            // 将返回信息进行强转
            CmppSubmitResp resp=(CmppSubmitResp)msg;
            log.info("-------------接收到短信提交应答-------------");
            log.info("----自增id："+resp.getSequenceId());
            log.info("----状态："+ resp.getState());
            log.info("----第一次响应："+resp.getMsgId2());

            ControlWindow controlWindow = ControlWindow.getInstance();// 获取临时窗口
            StandardSubmit submit = (StandardSubmit)controlWindow.remove(resp.getSequenceId());// 通过sequenceId获取到了消费者临时存储的对象

            ReportMatch reportMatch = ReportMatch.getInstance();  // 创建临时存储窗口
            reportMatch.put(resp.getMsgId2(),submit);   // 将submit以msgId2作为key存储


            MTQueue mtQueue = MTQueue.getInstance();   // 创建一个基于LinkedList实现的队列
            submit.setMsgid(String.valueOf(resp.getMsgId2()));    // 给submit封装msgid，数据全了。
            mtQueue.add(submit);  // 将submit添加到队列中
        }


        // 第二次响应，状态报告的通知
        if (msg instanceof CmppDeliver){
            CmppDeliver resp=(CmppDeliver)msg;
            // 是否为状态报告 0：非状态报告1：状态报告
            if (resp.getRegistered_Delivery() == 1) {
                // 如果是状态报告的话
                log.info("-------------状态报告---------------");
                log.info("----第二次响应："+resp.getMsg_Id_DELIVRD());
                log.info("----手机号："+resp.getDest_terminal_Id());
                log.info("----状态："+resp.getStat());

                StatQueue statQueue = StatQueue.getInstance();
                statQueue.add(msg);
            } else {
                //用户回复会打印在这里
                log.info(""+ MsgUtils.bytesToLong(resp.getMsg_Id()));
                log.info(resp.getSrc_terminal_Id());
                log.info(resp.getMsg_Content());
            }
        }
    }

}
